﻿using MediatR;
using RBAC.Domain.RBAC;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.Permission;

namespace RBAC.Write.Api.Application.Handler.Permission
{
    public class DeletePermissionHandler:IRequestHandler<DeletePermissionCommand, APIResult<int>>
    {
        private readonly IBaseRepository<PermissionModel> _permissionRepository;

        private readonly ILogger<DeletePermissionHandler> _logger;

        public DeletePermissionHandler(IBaseRepository<PermissionModel> permissionRepository, ILogger<DeletePermissionHandler> logger)
        {
            _permissionRepository = permissionRepository;
            _logger = logger;
        }
        /// <summary>
        /// 删除权限
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(DeletePermissionCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res=new APIResult<int>();
            var permission = _permissionRepository.GetModel(request.Id);
            if(permission!=null)
                permission.IsDeleted = true;
            var r = _permissionRepository.Update(permission);
            if (r > 0)
            {
                res.Data = r;
                res.Code = APIEnums.Success;
                res.Msg = "删除成功";
                _logger.LogInformation("删除成功");
                return Task.FromResult(res);
            }
            else
            {
                res.Code = APIEnums.Fail;
                res.Msg = "删除失败";
                _logger.LogError("删除失败");
                return Task.FromResult(res);
            }
        }
    }
}
